# 在这里写上你的代码 :-)
# -*- coding:utf-8 -*-
# 导入相关模块
from machine import Pin,PWM
import bluetooth,ble_uart_peripheral

class BluetoothShip:
    # 蓝牙模式，通过手机蓝牙连接机器人进行控制
    def __init__(self):
        # 配置蓝牙信息并开启蓝牙通信
        self.ble = bluetooth.BLE()
        self.uart = ble_uart_peripheral.BLEUART(self.ble,name='Boat')
        self.Ship = ShipControl()

        self.ble_control()  # 开启蓝牙控制

    def ble_control(self):
        # 用于接收手机控制命令
        Pin(2, Pin.OUT).value(0)  # 初始化蓝牙指示灯
        while True:
            if self.uart.any():  # 查询是否有信息
                self.text = str(self.uart.read(1).decode())  # 默认单次最多接收128字节
                Pin(2, Pin.OUT).value(1)
                print(self.text)
                try:
                    self.Ship.ShipRun(self.text)
                except:
                    pass

class ShipControl:
    def __init__(self):
        #左电机
        self.L1 = PWM(Pin(32), freq=1000, duty=0)
        self.L2 = PWM(Pin(33), freq=1000, duty=0)

        #右电机
        self.R1 = PWM(Pin(25), freq=1000, duty=0)
        self.R2 = PWM(Pin(26), freq=1000, duty=0)
        #RelayPin
        self.E1 = Pin(27, Pin.OUT)
        self.E2 = Pin(14, Pin.OUT)
        self.Stop()
        self.StopEat()
        self.speed=800

    def Go(self):
        self.L1.duty(self.speed)
        self.L2.duty(0)
        self.R1.duty(self.speed)
        self.R2.duty(0)

    def Back(self):
        self.L1.duty(0)
        self.L2.duty(self.speed)
        self.R1.duty(0)
        self.R2.duty(self.speed)

    def Left(self):
        self.L1.duty(self.speed)
        self.L2.duty(0)
        self.R1.duty(0)
        self.R2.duty(self.speed)

    def Right(self):
        self.L1.duty(0)
        self.L2.duty(self.speed)
        self.R1.duty(self.speed)
        self.R2.duty(0)

    def Stop(self):
        self.L1.duty(0)
        self.L2.duty(0)
        self.R1.duty(0)
        self.R2.duty(0)

    def Eat(self):
        self.E1.value(0)
        self.E2.value(1)

    def StopEat(self):
        self.E1.value(0)
        self.E2.value(0)

    def ShipRun(self, text):
        command = text
        if command == "c":  # 停止命令
            print('c')
            Pin(2, Pin.OUT).value(0)
            self.Stop()
        elif command == "f":  # 前进命令
            LED.value(1)
            self.Go()
        elif command == "b":  # 后退命令
            LED.value(1)
            self.Back()
        elif command == "l":  # 左转命令
            LED.value(1)
            self.Left()
        elif command == "r":  # 右转命令
            LED.value(1)
            self.Right()
        elif command == "e":  # 吃垃圾命令
            self.Eat()
        elif command == "n":  # 停止吃垃圾命令
            self.StopEat()

        else:
            return False


ship = BluetoothShip()